// quick.hxx


#ifndef _BLOGS_QUICK
#define _BLOGS_QUICK


#include <type_traits>

#include "array.hxx"
#include "comparable.hxx"
#include "std_out.hxx"
#include "std_random.hxx"


namespace blogs
{


class Quick
{

  private:

    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    void
    __sort__(Array<_T> & a, int lo, int hi)
    {
        if (hi <= lo) return;
        int j = __partition__(a, lo, hi);
        __sort__(a, lo, j-1);
        __sort__(a, j+1, hi);
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    int
    __partition__(Array<_T> & a, int lo, int hi)
    {
        int i = lo, j = hi+1;
        _T v = a[lo];
        while (true) {
            while (__less__(a[++i], v)) if (i == hi) break;
            while (__less__(v, a[--j])) if (j == lo) break;
            if (i >= j) break;
            __exch__(a, i, j);
        }
        __exch__(a, lo, j);
        return j;
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    bool
    __less__(_T const& v, _T const& w)
    {
        return v.compare_to(w) < 0;
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    void
    __exch__(Array<_T> & a, int i, int j)
    {
        _T t = a[i];
        a[i] = a[j];
        a[j] = t;
    }


  public:

    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    void
    sort(Array<_T> & a)
    {
        Std_Random::shuffle(a);
        __sort__(a, 0, a.size()-1);
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    bool
    is_sorted(Array<_T> const& a)
    {
        int N = a.size();
        for (int i = 1; i < N; ++i)
            if (__less__(a[i], a[i-1])) return false;
        return true;
    }


    template
    <
        class _T,
        class = typename std::enable_if<std::is_base_of<Comparable<_T>, _T>::value>::type
    >
    static
    void
    show(Array<_T> const& a)
    {
        Std_Out::println(a);
    }

};


} // end of namespace blogs


#endif

